import axios from 'axios';
import { ElLoading } from 'element-plus';

const isPro = import.meta.env.PROD;
const baseURL = isPro ? 'https://server.gongkaotongmeng.com:18089' : 'http://192.168.13.2:8089';
// const baseURL = isPro ? 'https://server.gongkaotongmeng.com:18089' : 'http://127.0.0.1:8089';

let loadingInstance;
const arr = ['/shenlun-cailiao/add'];

export function request(config) {
	const instance = axios.create({
		baseURL,
		timeout: 50000 * 60
	});

	// 请求拦截
	instance.interceptors.request.use(
		config => {
			console.log(config.url);
			// if (!arr.includes(config.url)) {
				loadingInstance = ElLoading.service({
					lock: true,
					text: '加载中...',
					background: 'rgba(0, 0, 0, 0.2)'
				});
			// }
			// 显示loading

			let token = localStorage.getItem('token');
			if (token) {
				config.headers['Authorization'] = token;
			}
			return config;
		},
		err => {
			loadingInstance?.close();
			console.log(err);
		}
	);

	//响应拦截
	instance.interceptors.response.use(
		res => {
			// 关闭loading
			loadingInstance?.close();
			return res.data;
		},
		err => {
			// 发生错误时也要关闭loading
			loadingInstance?.close();
			console.log(err);
		}
	);

	return instance(config);
}
